$(() => {

  let $width = $('#width'), 
      $height = $('#height'),
      $btnCal = $('#calc'),
      $form   = $('#main'), 
      $perimeter = $('#perimeter'),
      $widthValidate = $('#width-validate'),
      $heightValidate = $('#height-validate'),
      $area = $('#area');

  //字符级校验
$width.keypress((e)=>{
    let key = e.key,
        val = e.target.value,
        pos = e.target.selectionStart;  //按键发生的位置

    //各种规则分开写
    //if(!isLegalKey(key,val,pos)){
      //e.preventDefault();
    //}
       
    
    // 将所有规则整合成一个字符表达式
    val = val.slice(0,pos) + key + val.slice(pos,val.length);
    if(!/^(0|[1-9]\d*)(\.\d+)?((e|E)(\+|-)?\d+)?$/.test(val)) e.preventDefault();
    
                                       
  });
  
  $height.keypress((e)=>{
      let key = e.key,
          val = e.target.value,
          pos = e.target.selectionStart;
      val = val.slice(0,pos) + key + val.slice(pos,val.length);
      if(!/^(0|[1-9]\d*)(\.\d+)?((e|E)(\+|-)?\d+)?$/.test(val)) e.preventDefault();
      
      //if(!isLegalKey(key,val,pos)){
        //e.preventDefault();         
      //} 
  });
  

  //字段级校验（调用focusout事件）
  //字段比较多时,利用事件冒泡机制 在容器上定义事件
  //$form.focusout((e)=>{
    //console.log(e.target);
  //});
  //字段少
  $width.focusout(()=>{
    if(!validate($width,$widthValidate)){
      $width.select();          
    }
  });
  
  $height.focusout(()=>{
    if(!validate($height,$heightValidate)){
      $height.select();             
    }     
  });

  
  $btnCal.click(() => {

    let w = Number($width.val());
    let h = Number($height.val());
    
    //validate校验
    if(validate($width,$widthValidate) && validate($height,$heightValidate)){
      let p = (w+h)*2,
          a = w * h;

      $perimeter.val(p);
      $area.val(a);
    }

  });  
});

function validate(input,output){

  //is empty 是否为空
  if(input.val() === ''){
    output.html('该字段不能为空');
    return false;
  }else{
    output.html('');
  }
  
  //is number 是否为数字
  let val = Number(input.val()); 
  if(isNaN(val)){
    output.html('该字段应该是数值');
    return false;            
  } else{
    output.html('');
  }
  
  //is +  是否大于0
  if(val <= 0){
    output.html('该数值不能小于等于0');
    return false;            
  }else{
    output.html('');    
  }

  return true;
}
